﻿

namespace gozer
{
    internal struct Header
    {
        public const byte Length = 2;
        private byte _keyLength;
        private byte _valueLength;

        private Header(byte[] Bytes)
        {
            _keyLength = Bytes[0];
            _valueLength = Bytes[1];
        }

        public byte KeyLength
        {
            get
            {
                return _keyLength;
            }
            set
            {
                _keyLength = value;
            }
        }

        public byte ValueLength
        {
            get
            {
                return _valueLength;
            }
            set
            {
                _valueLength = value;
            }
        }

        /// <summary>
        /// The length of the header itself, plus the lengths of the key and value it references.
        /// </summary>
        public short TotalLength
        {
            get
            {
                return (short)(Length + KeyLength + ValueLength);
            }
        }

        public static Header Parse(byte[] Bytes)
        {
            return new Header(Bytes);
        }

        public static bool TryParse(byte[] Bytes, out Header Header)
        {
            Header = new Header();

            if (Bytes.Length != Length)
                return false;

            if (Bytes[0] == 0)
                return false;

            Header = Parse(Bytes);

            return true;
        }

        public byte[] GetBytes()
        {
            return new byte[2] { KeyLength, ValueLength };
        }
    }
}
